<script setup lang="ts">
import {defineProps, onBeforeMount, onMounted, reactive, ref} from 'vue'
import {get, deLete, put_json, post_json} from '@/assets/ts/ruquestMethod'
import type {AddressData, Address, Account, Cart} from "@/assets/ts/Interfaces";
import {ElMessage} from "element-plus";
const props = defineProps({
  username : String
})
const orderDia = ref(false)
const address = ref('')
const addressesData = reactive<AddressData>({
  data : [{
    id : 0,
    username : '',
    name : '',
    province : '',
    city : '',
    district : '',
    address : ''
  }]
})
const cart = reactive({
  username : '',
  descn : '',
  itemId : '',
  productName : '',
  num : 0,
  listprice: 0,
  totalcost: 0,
  productId: ''
})
let cartItem = reactive({
  data : [{
    username : '',
    descn : '',
    itemId : '',
    productName : '',
    num : 0,
    listprice: 0,
    totalcost: 0,
    productId: ''
  }],
  cost : 0
})

const getCart = () =>{
  get('/carts',
      (data:any) =>{
        cartItem.data=data.data
        let cost=0;
        cartItem.data.map(item => {
          cost += item.totalcost;
        })
        cartItem.cost = cost
      })
}

const handleEdit = ( row: Cart) => {
  row.totalcost = row.listprice * row.num
  let cost=0;
  cartItem.data.map(item => {
    cost += item.totalcost;
  })
  cartItem.cost = cost
  put_json("/carts", row, (res:any)=>{
    console.log(res)
  })
}
const handleDelete = (index: number, row: Cart) => {
  deLete(`/carts/${row.itemId}`, ()=>{
    getCart()
    let cost=0;
    cartItem.data.map(item => {
      cost += item.totalcost;
    })
    cartItem.cost = cost
  })
}
const getAddress = () =>{
  get('/addresses',
      (response : any) => {
        if(response.status == 1){
          addressesData.data = response.data
        }
      }
  )
}
const changeNum = ()=>{
  cart.totalcost = cart.listprice*cart.num
}
const showDia = (row:Cart) => {
  cart.num = row.num
  cart.totalcost = row.totalcost as number
  cart.listprice = row.listprice
  cart.itemId = row.itemId
  cart.productId = row.productId
  cart.descn = row.descn
  cart.productName = row.productName
  orderDia.value =true
  getAddress()
}
const buy = ()=>{
  if(address.value == ''){
    ElMessage.warning('请选择地址')
    return
  }
  post_json('/orders',
      {
        username: sessionStorage.getItem('loginName'),
        descn: cart.descn,
        productid:cart.productId,
        itemid:cart.itemId,
        num:cart.num,
        total_cost:cart.totalcost,
        productname:cart.productName,
        address: address.value
      },
      (res:any)=>{
        ElMessage.success('下单成功')
        getCart()
        console.log(res)
        orderDia.value = false
  })
}
onBeforeMount(() =>{
  getCart()
})
</script>

<template>
  <h2>购物车</h2>
  <el-table stripe :data="cartItem.data" style="width: 100%" fit>
    <el-table-column  width="120" >
      <template #default="scope">
        <el-image :src="scope.row.descn"></el-image>
      </template>
    </el-table-column>
    <el-table-column prop="itemId" label="物品id" width="120" />
    <el-table-column prop="productName" label="宠物名" width="120" />
    <el-table-column prop="num" label="数量" >
      <template #default="scope">
        <el-input-number v-model="scope.row.num" :min="1"  @change="handleEdit(scope.row)" />
      </template>
    </el-table-column>
    <el-table-column prop="listprice" label="单价" width="120" >
      <template #default="scope">
        <span style="font-weight: bold;color: rgb(255, 79, 0);"> ￥{{scope.row.listprice}}</span>
      </template>
    </el-table-column>
    <el-table-column prop="totalcost" label="总价格" width="120" />
    <el-table-column prop="productId" label="物品id" width="120" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
            size="small"
            type="primary"
            @click="showDia(scope.row)"
        >下单</el-button
        >
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <span style="padding: 10px 0;float: left">
    商品总价:
    <span class="cost">￥{{cartItem.cost}}</span>
  </span>
  <el-dialog
      v-model="orderDia"
      :title="`购买${cart.itemId}--${cart.productName}`"
      width="30%"
  >
    <el-radio-group v-model="address"
                    size="small"
                    style="display: flex;flex-direction: column;text-align: center">
      <el-radio v-for="item in addressesData.data"
                class="address-choose"
                :label="`${item.province}省${item.city}市${item.district}区${item.address}`" border>
        收件人:{{item.name}}<br/>
        详细地址:{{item.province}}省{{item.city}}市{{item.district}}区{{item.address}}
      </el-radio>
    </el-radio-group>
    <span>单价:<span style="font-weight: bold;color: rgb(255, 79, 0);">￥{{cart.listprice}}</span></span><br/>
    <el-input-number v-model="cart.num" :min="1" @change="changeNum"/><br/>
    <span>总价:<span style="font-weight: bold;color: rgb(255, 79, 0);">￥{{cart.totalcost}}</span></span>
    <template #footer>
                <span class="dialog-footer">
                    <el-button @click="orderDia = false">取消</el-button>
                    <el-button type="primary" @click="buy">
                        购买
                    </el-button>
                </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.cost{
  font-weight: bold;
  color: rgb(255, 79, 0);
  font-size: 20px;
}
.address-choose {
  min-height: 40px;
  margin: 10px 0;
}
</style>